<template>
  <div>
    <el-card id="search">
      <el-input v-model="searchModel.username" placeholder="按用户名查询" clearable></el-input>
      <el-input v-model="searchModel.phone" placeholder="按电话查询" clearable></el-input>
      <el-button type="primary" round icon="el-icon-search" @click="getUserList">查询</el-button>
      <el-button type="primary" icon="el-icon-plus" circle id="add" @click="EditAddUI"></el-button>
    </el-card>

    <el-card>
      <el-table
        :data="userList"
        style="width: 100%">
        <el-table-column
          label="#"
          width="80">
          <template slot-scope="scope">
            {{ (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column
          prop="id"
          label="用户ID"
          width="80">
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="电话"
          width="180">
        </el-table-column>
        <el-table-column
          prop="status"
          label="用户状态"
          width="180">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 1">正常</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          label="操作"
          width="180">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" circle size="mini" @click="EditUpdateUI(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="deleteById(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clearForm">
      <el-form :model="userForm" :rules="rules" ref="userFormRef">
        <el-form-item label="用户名" prop="username" :label-width="formLabelWidth" style="width: 400px;">
          <el-input v-model="userForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" :label-width="formLabelWidth" style="width: 400px;" v-if="userForm.id == null || userForm.id == undefined">
          <el-input v-model="userForm.password" autocomplete="off" type="password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone" :label-width="formLabelWidth" style="width: 400px;">
          <el-input v-model="userForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户状态" :label-width="formLabelWidth" style="width: 400px;" >
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item label="用户角色" :label-width="formLabelWidth" style="width: 400px;">
          <el-checkbox-group
            v-model="userForm.roleIdList"
            :min="0"
            :max="2">
            <el-checkbox v-for="role in roleList" :label="role.roleId" :key="role.roleId">{{ role.roleDesc }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth" style="width: 400px;">
          <el-input v-model="userForm.email" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userManage from '@/api/userManage'
import roleManager from '@/api/roleManager'

export default {
  data() {
    var checkEmail = (rule, value, callback) => {
      var patt = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
      if (!patt.test(value)) {
        return callback(new Error('邮箱不合法'))
      }
      callback();
    }
    return {
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入电子邮件', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      roleList: [],
      formLabelWidth: '130px',
      dialogFormVisible: false,
      userForm: {
        roleIdList: []
      },
      title: '',
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 5,
        username: '',
        phone: ''
      },
      userList: []
    }
  },
  methods: {
    getAllRole() {
      roleManager.getAllRole().then(response => {
        this.roleList = response.data
      })
    },
    clearForm() {
      this.userForm = {
        roleIdList: []
      }
      this.$refs.userFormRef.clearValidate()
    },
    EditAddUI() {
      this.title = '新增用户'
      this.dialogFormVisible = true
    },
    EditUpdateUI(id) {
      this.title = '修改用户'
      this.dialogFormVisible = true
      userManage.getUserById(id).then(response => {
        this.userForm = response.data
      })
    },
    deleteById(user) {
      this.$confirm(`此操作将永久删除用户 ${user.username}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userManage.deleteUser(user.id).then(response => {
          this.$message({
            type: 'success',
            message: response.message
          });
          this.getUserList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addUser() {
      this.$refs.userFormRef.validate((valid) => {
        if (valid) {
          // alert(123)
          userManage.saveUser(this.userForm).then(response => {
            this.$message({
              message: response.message,
              type: 'success'
            })
            this.dialogFormVisible = false
            this.getUserList()
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getUserList() {
      userManage.getUserList(this.searchModel).then(response => {
        this.total = response.data.total
        this.userList = response.data.rows
      })
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize
      this.getUserList()
    },
    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo
      this.getUserList()
    }
  },
  created() {
    this.getUserList()
    this.getAllRole()
  }
}
</script>

<style scoped>
  #search .el-input{
    width: 200px;
    margin-right: 10px;
  }

  #add {
    float: right;
  }
</style>
